package com.geezdata.cps.sdk3rd.jushita;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.base.utils.Md5Util;
import com.geezdata.cps.sdk3rd.common.domain.BaseOrder;
import com.geezdata.cps.sdk3rd.common.response.BaseOrderListResult;
import com.geezdata.cps.sdk3rd.jushita.request.JushitaRequest;

public class JushitaDefaultClient implements JushitaClient {
    private String appKey;
    private String appSecret;
    private String serverUrl;
    
    public JushitaDefaultClient(String serverUrl, String appKey, String appSecret) {
		super();
		this.serverUrl = serverUrl;
		this.appKey = appKey;
		this.appSecret = appSecret;
	}
    
	@SuppressWarnings("unchecked")
	public <T extends BaseOrder> BaseResponse<BaseOrderListResult<T>> execute(JushitaRequest request) {
        String rspStr = null;
        try {
            rspStr = HttpClientUtil.post(serverUrl, prepareHttpParams(request));
        } catch (Exception e) {
        	return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), e.getMessage());
        }
        
        JSONObject jsonObject = JSONObject.parseObject(rspStr); 
        BaseOrderListResult<T> juShiTaResult = (BaseOrderListResult<T>) JSONObject.toJavaObject(
        		jsonObject.getJSONObject("result"), request.getResponseClass());
        return BaseResponse.success(juShiTaResult);
    }
    
    private Map<String, Object> prepareHttpParams(JushitaRequest request) {
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("appKey", appKey);
        params.put("appSecret", Md5Util.md5(appSecret));
        params.put("method_name", request.getMethodName());
        params.put("seller_nick", request.getSellerNick());
        params.put("start_time", request.getStartTime());
        params.put("end_time", request.getEndTime());
        params.put("last_tid", request.getLastTid());
        return params;
    }
}
